package com.campus.dao.impl;

import com.campus.dao.TeacherDao;
import com.campus.model.Teacher;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

@Repository
@Slf4j
public class TeacherDaoImpl implements TeacherDao {

    private final JdbcTemplate jdbcTemplate;

    public TeacherDaoImpl(JdbcTemplate jdbcTemplate) {
        this.jdbcTemplate = jdbcTemplate;
    }

    @Override
    public int createTeacher(Teacher teacher) {
        String sql = "INSERT INTO t_manager_teacher (teacher_name, subject, profession, school, introduce, login_id) VALUES (?, ?, ?, ?, ?, ?)";
        return jdbcTemplate.update(sql,
                teacher.getTeacherName(),
                teacher.getSubject(),
                teacher.getProfession(),
                teacher.getSchool(),
                teacher.getIntroduce(),
                teacher.getLoginId());
    }

    @Override
    public Teacher getTeacherById(int id) {
        String sql = "SELECT * FROM t_manager_teacher WHERE id = ?";
        return jdbcTemplate.queryForObject(sql, new Object[]{id}, (rs, rowNum) -> {
            Teacher teacher = new Teacher();
            teacher.setId(rs.getInt("id"));
            teacher.setTeacherName(rs.getString("teacher_name"));
            teacher.setSubject(rs.getString("subject"));
            teacher.setProfession(rs.getString("profession"));
            teacher.setSchool(rs.getString("school"));
            teacher.setIntroduce(rs.getString("introduce"));
            teacher.setLoginId(rs.getInt("login_id"));
            return teacher;
        });
    }

    @Override
    public List<Teacher> getTeachersByFilter(String subject, String school) {
        StringBuilder sql = new StringBuilder("SELECT * FROM t_manager_teacher WHERE 1=1");
        if (subject != null && !subject.isEmpty()) {
            sql.append(" AND subject = '").append(subject).append("'");
        }
        if (school != null && !school.isEmpty()) {
            sql.append(" AND school = '").append(school).append("'");
        }
        return jdbcTemplate.query(sql.toString(), (rs, rowNum) -> {
            Teacher teacher = new Teacher();
            teacher.setId(rs.getInt("id"));
            teacher.setTeacherName(rs.getString("teacher_name"));
            teacher.setSubject(rs.getString("subject"));
            teacher.setProfession(rs.getString("profession"));
            teacher.setSchool(rs.getString("school"));
            teacher.setIntroduce(rs.getString("introduce"));
            teacher.setLoginId(rs.getInt("login_id"));
            return teacher;
        });
    }
}
